/**   
 * @ClassName: LoginController.java 
 * @Package com.vrv.controller 
 * @author LQ   
 * @date 2017年3月17日 上午12:34:39 
 * @version V1.0
 */
package com.vrv.controller.login;

import java.io.IOException;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.vrv.common.util.result.ResultMapper;
import com.vrv.util.ShiroUtils;

/** 
 * LoginController:登录Controller
 * @author LQ 
 */
@Controller
public class LoginController {
    
    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @param captcha 验证码
     * @return ResultMapper 映射结果
     */
    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public ResultMapper login(String username, String password, String captcha)throws IOException {
        
        String kaptcha = com.vrv.util.ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
        if(!captcha.equalsIgnoreCase(kaptcha)){
            return ResultMapper.error("验证码不正确");
        }
        
        try{
            Subject subject = ShiroUtils.getSubject();
            //sha256加密
            //password = new Sha256Hash(password).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        }catch (UnknownAccountException e) {
            return ResultMapper.error(e.getMessage());
        }catch (IncorrectCredentialsException e) {
            return ResultMapper.error(e.getMessage());
        }catch (LockedAccountException e) {
            return ResultMapper.error(e.getMessage());
        }catch (AuthenticationException e) {
            return ResultMapper.error("账户验证失败");
        }
        return ResultMapper.ok();
        
    }
    
}
